DROP PROCEDURE IF EXISTS Create_Index;

DELIMITER $$

CREATE PROCEDURE Create_Index()
BEGIN
<#if tableList??&&(tableList?size>0)>
    <#list tableList as t>
        <#if t.tableIndexes?? && (t.tableIndexes?size > 0) >
            <#list t.tableIndexes as indexes>
                BEGIN
                DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
                BEGIN
                GET  DIAGNOSTICS CONDITION 1 @errno = MYSQL_ERRNO, @msg = MESSAGE_TEXT;
                select @errno,@msg;
                END;
                IF NOT EXISTS (SELECT * FROM information_schema.statistics WHERE table_schema = '${databaseName}' AND table_name = '${t.name}' AND index_name = '${indexes.indexesName}')
                THEN
                <#if indexes.indexesType == "INDEX">
                    set @statement = CONCAT("ALTER TABLE ", " ${t.name} ", " ADD INDEX ", " ${indexes.indexesName} ", "(", " ${indexes.indexesColumn} ", "  )");
                </#if>
                <#if indexes.indexesType == "UNIQUE_INDEX">
                    set @statement = CONCAT("ALTER TABLE ", "${t.name}", " ADD UNIQUE INDEX ", "${indexes.indexesName}", "(", "${indexes.indexesColumn}", "  )");
                </#if>
                PREPARE STMT FROM @statement;
                EXECUTE STMT;
                END IF;
                END;

            </#list>
        </#if>

    </#list>
</#if>

END;

CALL Create_Index;
DROP PROCEDURE Create_Index;

$$